package com.caiya.fallback;

import com.caiya.cart.Res;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * Zuul 回退类
 * Created by Administrator on 2019/4/3 0003.
 */
public class MyFallbackProvider implements FallbackProvider{


    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return this.response(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    public ClientHttpResponse fallbackResponse(Throwable throwable) {
        if (throwable instanceof HystrixTimeoutException){
            return response(HttpStatus.GATEWAY_TIMEOUT);
        }else {
            return this.fallbackResponse();
        }
    }

    private ClientHttpResponse response(final HttpStatus status) {
     return new ClientHttpResponse() {
         @Override
         public HttpStatus getStatusCode() throws IOException {
             return status;
         }

         @Override
         public int getRawStatusCode() throws IOException {
             return status.value();
         }

         @Override
         public String getStatusText() throws IOException {
             return status.getReasonPhrase();
         }

         @Override
         public void close() {

         }

         @Override
         public InputStream getBody() throws IOException {
             return new ByteArrayInputStream("服务器已挂，稍后再试".getBytes());
         }

         @Override
         public HttpHeaders getHeaders() {
             HttpHeaders httpHeaders = new HttpHeaders();
             MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));
             httpHeaders.setContentType(mt);
             return httpHeaders;
         }
     };
    }
}
